package tgc.edu.tms.web.controller;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.tms.custom.TablePageable;
import tgc.edu.tms.custom.TimeUtils;
import tgc.edu.tms.entity.FlowTable;
import tgc.edu.tms.entity.WorkSheetCount;
import tgc.edu.tms.entity.WorkSheetTerm;
import tgc.edu.tms.service.FlowTableService;
import tgc.edu.tms.web.form.WorkSheetTermForm;

/**
 * @className: WorkSheetTermController
 * @description: 学期工作表的控制器
 * @author: JavaJun
 * @date: 2019年1月8日
 */
@Controller
@RequestMapping(value = "/worksheetterm")
public class WorkSheetTermController {

	@Autowired
	private FlowTableService flowTableService;

	@RequestMapping(value = "/manage")
	public void manage(ModelMap map) {
		List<String> allTerm = allTerm();
		List<String> allYear = allYear();
		map.put("allYear", allYear);
		map.put("allTerm", allTerm);
	}

	@RequestMapping(value = "/page")
	@ResponseBody
	private Object page(TablePageable pageParam, WorkSheetTermForm form) {
		// 创建前台所需的数据
		HashMap<String, Object> result = new HashMap<>();
		/*
		 * if(!StringUtils.hasText(form.getYear()) &&
		 * !StringUtils.hasText(form.getTerm())) { DateFormat format = new
		 * SimpleDateFormat("yyyy"); form.setYear(format.format(new Date()));
		 * System.out.println(form.getYear()); }
		 */
		// 所有老师
		List<String> allTeacher = flowTableService.findTeacher();
		int total = 0;
		List<WorkSheetTerm> content = new ArrayList<>();
		for (String teacher : allTeacher) {
			/* WorkSheetTermForm wform = new WorkSheetTermForm(); */
			Double a = (double) 0;
			List<Object[]> cout = flowTableService.findTerm(form.getTerm(), teacher);
			for (int i = 0; i < cout.size(); i++) {
				Object[] z = cout.get(i);
				BigInteger q = (BigInteger) z[6];
				Integer p = q.intValue();
				WorkSheetCount workSheet = new WorkSheetCount((String) z[0], (String) z[1], (String) z[2],
						(Integer) z[3], (Boolean) z[5], (Integer) z[4], p);

				a = workSheet.getZhxs() * workSheet.getYfbxs() + a;
			}
			total += 1;
			WorkSheetTerm term = new WorkSheetTerm();
			term.setId(total);
			term.setTeacher(teacher);
			if (!StringUtils.hasText(form.getTerm())) {
				term.setTerm(TimeUtils.getxq());
			} else {
				term.setTerm(form.getTerm());
			}
			term.setComplete(a);
			content.add(term);
			/*
			 * BeanUtils.copyProperties(form, wform); wform.setTeacher(teacher);
			 * List<FlowTable> list = flowTableService.findAll(buildSpec(wform));
			 * List<String> termList = new ArrayList<>(); for (FlowTable otf : list) {
			 * Boolean flag = false; for (String termL : termList) {
			 * if(otf.getTerm().equals(termL)) { flag = true; break; } } if(!flag) {
			 * termList.add(otf.getTerm()); } } //
			 * System.out.println("termList:"+termList.size()); // for(String r : termList)
			 * { // System.out.println(r); // } if(termList.size() > 1) { for (String term :
			 * termList) { WorkSheetTermForm w2form = new WorkSheetTermForm();
			 * BeanUtils.copyProperties(wform, w2form); w2form.setTerm(term);
			 * List<FlowTable> list2 = flowTableService.findAll(buildSpec(w2form)); try {
			 * WorkSheetTerm sheetTerm = new WorkSheetTerm();
			 * sheetTerm.setTerm(list2.get(0).getTerm()); total += 1;
			 * sheetTerm.setId(total); sheetTerm.setComplete(list2.size());
			 * sheetTerm.setTeacher(teacher); content.add(sheetTerm); } catch (Exception e)
			 * {
			 * 
			 * } } } else {
			 * 
			 * try { WorkSheetTerm sheetTerm = new WorkSheetTerm();
			 * sheetTerm.setTerm(list.get(0).getTerm()); total += 1; sheetTerm.setId(total);
			 * sheetTerm.setComplete(list.size()); sheetTerm.setTeacher(teacher);
			 * content.add(sheetTerm); } catch (Exception e) { System.out.println("size为0");
			 * }
			 * 
			 * }
			 */

		}
		result.put("total", total);
		result.put("rows", content);
		return result;
	}

	/**
	 * 根据老师进行分组，如果老师名字一样，则会出现逻辑问题 出现逻辑问题的原因在于教师在数据库中是一个字符串，老师名字一致时，无法判断不是同一老师
	 * 
	 * @param form
	 * @return
	 */
	private List<FlowTable> allTeacherOneLog(WorkSheetTermForm form) {
		WorkSheetTermForm workSheetTermForm = new WorkSheetTermForm();
		// BeanUtils.copyProperties(form, workSheetTermForm);
		workSheetTermForm.setTerm(form.getTerm());
		workSheetTermForm.setGroupBy("1");
		List<FlowTable> allteacher = flowTableService.findAll(buildSpec(workSheetTermForm));
		List<String> allTeacher = new ArrayList<>();
		for (FlowTable flowTable : allteacher) {
			String teacher = flowTable.getTeacher();
			allTeacher.add(teacher);
		}
		return allteacher;
	}

	/**
	 * 在 FlowTable 表格中查找所有的老师，返回所有老师的名字集合
	 * 
	 * @param form
	 * @return
	 */
	private List<String> allTeacher(WorkSheetTermForm form) {
		List<FlowTable> allTeacherOneLog = allTeacherOneLog(form);
		List<String> allTeacher = new ArrayList<>();
		for (FlowTable flowTable : allTeacherOneLog) {
			String teacher = flowTable.getTeacher();
			allTeacher.add(teacher);
		}
		return allTeacher;
	}

	/**
	 * 所有的学期 如果没有含有上课内容的，则会没有数据
	 * 
	 * @return 所有的学期
	 */
	private List<String> allTerm() {
		WorkSheetTermForm wform = new WorkSheetTermForm();
		wform.setGroupByTerm("1");
		List<FlowTable> list = flowTableService.findAll(buildSpec(wform));
		List<String> allTerm = new ArrayList<>();
		for (FlowTable flowTable : list) {
			allTerm.add(flowTable.getTerm());
		}
		return allTerm;
	}

	private Specification<FlowTable> buildSpec(WorkSheetTermForm form) {
		Specification<FlowTable> spec = new Specification<FlowTable>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<FlowTable> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				// 上课内容不为空
				rules.add(cb.isNotNull(root.get("sknr")));

				// 根据老师名字 group by
				String groupBy = form.getGroupBy();
				if (StringUtils.hasText(groupBy)) {
					query.groupBy(root.get("teacher"));
				}

				// 学期 group by
				String groupByTerm = form.getGroupByTerm();
				if (StringUtils.hasText(groupByTerm)) {
					query.groupBy(root.get("term"));
				}

				/*
				 * String teacher = form.getTeacher(); if(StringUtils.hasText(teacher)) {
				 * rules.add(cb.equal(root.get("teacher"), teacher)); }
				 */

				// 老师
				String teacher = form.getTeacher();
				if (StringUtils.hasText(teacher)) {
					rules.add(cb.equal(root.get("teacher"), teacher));
				}

				// 学期
				String term = form.getTerm();
				// 学年
				String year = form.getYear();
				// 搜索
				String search = form.getSearch();

				if (StringUtils.hasText(term) && !StringUtils.hasText(year)) {
					rules.add(cb.like(root.get("term"), "%" + term + "%"));
				}

				if (StringUtils.hasText(year) && !StringUtils.hasText(term)) {
					rules.add(cb.like(root.get("term"), "%" + year + "%"));
				}

				if (StringUtils.hasText(term) && StringUtils.hasText(year)) {
					rules.add(cb.like(root.get("term"), "%" + term + "%"));
				}

				/*
				 * if(StringUtils.hasText(search)) { rules.add(cb.like(root.get("term"), "%" +
				 * search + "%")); }
				 */

				query.where(cb.and(rules.toArray(new Predicate[rules.size()])));

				return query.getRestriction();
			}
		};
		return spec;
	}

	public List<String> allYear() {
		List<FlowTable> allList = flowTableService.findAll();
		List<String> fullTime = new ArrayList<>();
		for (FlowTable flow : allList) {
			String timeStr = flow.getTime();
			try {
				String[] split = timeStr.split("-");
				fullTime.add(split[0]);
			} catch (Exception e) {

			}

		}
		List<String> yearList = new ArrayList<>();
		for (String full : fullTime) {
			Boolean flag = false;

			for (String yyear : yearList) {
				if (yyear.equals(full)) {
					flag = true;
					break;
				}
			}

			if (!flag) {
				yearList.add(full);
			}
		}
		return yearList;
	}

}
